package com.dcy.workflow.service;

import com.dcy.common.model.PageModel;
import com.dcy.common.model.PageResult;
import com.dcy.workflow.dao.ActProcessDao;
import com.dcy.workflow.vo.in.ProcessDefinitionSearchInVO;
import com.dcy.workflow.vo.out.ProcessDefinitionListOutVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.springframework.stereotype.Service;

/**
 * @author dcy
 * @description 流程service
 * @createTime 2022/12/22 9:31
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class ActProcessService {

    private final ActProcessDao actProcessDao;
    private final RepositoryService repositoryService;
    private final RuntimeService runtimeService;
    private final HistoryService historyService;

    /**
     * 流程定义分页列表
     *
     * @param processDefinitionSearchInVO
     * @param pageModel
     * @return
     */
    public PageResult<ProcessDefinitionListOutVO> processDefinitionPageList(ProcessDefinitionSearchInVO processDefinitionSearchInVO, PageModel pageModel) {
        return actProcessDao.processDefinitionPageList(processDefinitionSearchInVO, pageModel);
    }

    /**
     * 挂起、激活流程实例
     *
     * @param processDefinitionId
     * @return
     */
    public Boolean hangChange(String processDefinitionId) {
        // 判断挂起状态，true 挂起， false 未挂起
        if (repositoryService.isProcessDefinitionSuspended(processDefinitionId)) {
            // 激活
            repositoryService.activateProcessDefinitionById(processDefinitionId);
        } else {
            // 挂起
            repositoryService.suspendProcessDefinitionById(processDefinitionId);
        }
        return Boolean.TRUE;
    }

    /**
     * 删除部署的流程，级联删除流程实例
     *
     * @param deploymentId
     * @return
     */
    public Boolean deleteDeployment(String deploymentId) {
        repositoryService.deleteDeployment(deploymentId, true);
        return Boolean.TRUE;
    }

    /**
     * 删除流程
     *
     * @param processInstanceId
     * @return
     */
    public Boolean deleteProcess(String processInstanceId) {
        final long count = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).count();
        if (count > 0) {
            runtimeService.deleteProcessInstance(processInstanceId, "删除流程");
        }
        final long hisCount = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).count();
        if (hisCount > 0) {
            historyService.deleteHistoricProcessInstance(processInstanceId);
        }
        return Boolean.TRUE;
    }
}
